<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2022/9/1
 * Time: 22:10
 */

namespace App\Http\Controllers;
use App\Datas\AfLog;
use App\Datas\EventList;
use App\Datas\ModelList;
use App\Datas\Pay;
use App\Datas\System;
use App\Datas\User;
use App\Datas\Upgrade;
use App\Datas\UserOntrial;
use App\Tools\FunTool;
use App\Tools\Oppo;
use App\Tools\Oss;
use App\Tools\Huawei;
use App\Tools\IPFactory;
use App\Tools\Curl as CurlCommon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Ixudra\Curl\Facades\Curl;
use GeoIp2\Database\Reader;

use App\Datas\UserGoogleSubscribe;


class SystemController extends Controller
{
    protected $dataUser;
    protected $dataSystem;
    public function __construct()
    {
        $this->dataUser = new User();
        $this->dataSystem = new System();
    }
    public function init(Request $request) {
        $lange = $this->getLanage();
        if ($lange == 'zh') {
            $vipTxt = '低至0.01元/天，立享自定义画作，更高画质，以及无限生成次数';
        } else {
            $vipTxt = 'Join PRO, enjoy custom image content, faster and unlimited generation,Low as $0.01/day';
        }
        $data = [
            'user_protocol' => 'https://overseas-files.dalleai.art/system/terms-of-service-'.$lange.'.html',
            'privacy_protocol' => 'https://overseas-files.dalleai.art/system/privacy-'.$lange.'.html',
            'qr_url' => 'https://dalleai.art/qr.png',
            'vip_txt' => $vipTxt,
            'customer_service' => "dalleaiartist@gmail.com",
            'help_url' => 'https://overseas-files.dalleai.art/help/index-'.$lange.'.html',
            'count_down_member' => 3,
            'count_down_dot' => 0,
            'contribution_num' => config('app.contribution_num'),
			'high_drawing_dot' => FunTool::getHighDrawingDot(),// 高清 需要的点数
            'model_num' => ModelList::getInstance()->getAbleCount(),
            'video_url' => 'https://overseas-files.dalleai.art/init/Chinoiserie_2.mp4',
            'image_video_dot' => FunTool::getImageVideoDot(),//
            'is_can_handle_video' => 1
        ];
        $version = $this->getVersion();

        $oaid = $request->oaid ?? '';
        $imei = $request->imei ?? '';
        $idfa = $request->idfa ?? '';
        $aaid = $request->aaid ?? '';
        $vaid = $request->vaid ?? '';
        $platform = $request->platform ?? '';
        $channelId = $request->channel ?? '';
        $callback = $request->callback ?? '';
        $appsflyid = $request->appsflyid ?? '';

        $deviceId = $_SERVER['HTTP_GUID'] ?? '';

        $ip = $_SERVER['HTTP_ALI_CDN_REAL_IP'] ?? '';

        // 开始处理广告逻辑
        $tagArr = [];
        if (!empty($imei)) {
            $tagArr[] = $imei;
            $tagArr[] = md5($imei);
            //Log::info('init imei', [$imei]);
            //Log::info('init imeimd5', [md5($imei)]);
        }
        if (!empty($idfa)) {
            $tagArr[] = $idfa;
            $tagArr[] = md5($idfa);
            //Log::info('init idfa', [$idfa]);
            //Log::info('init idfamd5', [md5($idfa)]);
        }
        if (!empty($oaid) && $oaid != '00000000-0000-0000-0000-000000000000' && $oaid != '00000000000000000000000000000000') {
            $tagArr[] = $oaid;
            $tagArr[] = md5($oaid);
            //Log::info('init oaid', [$oaid]);
            //Log::info('init oaidmd5', [md5($oaid)]);
        }
        if (!empty($oaid) &&  strlen($oaid) >= 32 && $oaid != '00000000-0000-0000-0000-000000000000' && $oaid != '00000000000000000000000000000000') {
            $oiad32md5 = md5(substr(strtolower($oaid), 0,32));
            //Log::info('init oaid32md5', [$oiad32md5]);
            $tagArr[] = $oiad32md5;
        }
        if (!empty($vaid) && $vaid != '00000000-0000-0000-0000-000000000000' && $oaid != '00000000000000000000000000000000') {
            $tagArr[] = $vaid;
            $tagArr[] = md5($vaid);
            //Log::info('init vaid', [$vaid]);
            //Log::info('init vaidmd5', [md5($vaid)]);
        }
        if (!empty($aaid) && $aaid != '00000000-0000-0000-0000-000000000000' && $oaid != '00000000000000000000000000000000') {
            $tagArr[] = $aaid;
            $tagArr[] = md5($aaid);
            //Log::info('init aaid', [$aaid]);
            //Log::info('init aaidmd5', [md5($aaid)]);
        }
        if (!empty($ip)) {
            $tagArr[] = $ip;
            $tagArr[] = md5($ip);
            //Log::info('init ip', [$ip]);
            //Log::info('init ipmd5', [md5($ip)]);
        }


        $systemData = new System();

        $adData = null;
        foreach ($tagArr as $tag) {
            $adData = $systemData->getAdTag($tag);
            if (!empty($adData)) {
                break;
            }
        }

        $deviceInfo = $systemData->getDevice($deviceId);
        if (!$deviceInfo) {
            $cburl = $adData['cburl'] ?? '';
            $source = $adData['source'] ?? '';
            $adChannel = $adData['channel'] ?? '';
            $os = $adData['os'] ?? '';
            if (!empty($adData)) {
                $channelId = $adChannel;
            }

            $model = $this->getModel();

            //测试回传数据请求（华为设备）
            if ($callback != '' && substr($channelId, 0, 6) == 'huawei') {
                $cburl = $callback;
                $huawei = new Huawei();
                $huawei->dataRetrieval(1, $oaid, $callback);
            }

            //根据IP获取国家代码
            $sIP = IPFactory::Instance()->getClientIP();
            $sIPCountryCo = IPFactory::Instance()->getCountryCoByIP($sIP);
			$systemData->setDevice($deviceId, $channelId, $vaid, $aaid, $oaid, $imei, $idfa, '', $model, '', '', '', '', $platform, $cburl, $source, $version, $appsflyid, $sIP, $sIPCountryCo);

            // 广告回调
            if (!empty($cburl) && $source == 'toutiao') {
                Curl::to($adData['cburl'] . '&event_type=0')->get();
                //curlRequest($adData['cburl'] . '&event_type=0', null, 'GET');
            }
            if (!empty($cburl) && $source == 'kuaishou') {
                Curl::to($adData['cburl'] . '&event_type=1&event_time='.time() . '000')->get();
                //curlRequest($adData['cburl'] . '&event_type=1&event_time='.time() . '000', null, 'GET');
            }
            if (!empty($cburl) && $source == 'wangyi') {
                $convAction = ($platform=='ios') ? 'ios_activate' : 'android_activate';
                $res = Curl::to('http://conv.youdao.com/api/track?conv_ext='.$adData['cburl'].'&conv_action='.$convAction)->get();
                //$res = curlRequest('http://conv.youdao.com/api/track?conv_ext='.$adData['cburl'].'&conv_action='.$convAction, null, 'GET');
                //writeLog('ad', "广告|网易|激活|结果", [$deviceId, $adData, $res]);
            }
            if (!empty($cburl) && $source == 'bilibili') {
                $url = $cburl . '&conv_type=APP_FIRST_ACTIVE&conv_time='.time() . '000';
                $res = Curl::to($url)->get();
                //$res =curlRequest($adData['cburl'] . '&conv_type=APP_FIRST_ACTIVE&conv_time='.time() . '000', null, 'GET');
                //writeLog('ad', "广告|B站|激活|结果", [$deviceId, $adData, $res]);
                //Log::info('ad|bilibili|conv_time', [$deviceId, $url, $res]);
            }
            // if ($channelId == '60003') {
            //     $oppoTools = new Oppo();
            //     $oppoTools->sendData($imei, $oaid,'','',1,'', 0, $cburl);
            // }
            if ($channelId == 'oppo-01') {
                $oppoTools = new Oppo();
                $oppoTools->sendData($imei, $oaid,'','',1,'', 1, $cburl);
            }
        }else{
			//国家代码
			if(empty($deviceInfo['country_co'])) {
				//根据IP获取国家代码
				$sIP = IPFactory::Instance()->getClientIP();
				$sIPCountryCo = IPFactory::Instance()->getCountryCoByIP($sIP);
				$systemData->updateDevice($deviceId, ['ip' => $sIP, 'country_co' => $sIPCountryCo]);
			}
		}
        //appflysid变更
        if (!empty($deviceInfo) && $appsflyid != "" && $deviceInfo['appsfly_id']!= $appsflyid) {
            if ($systemData->checkAfidChange($deviceInfo)) {
                $systemData->setAppsflyid($deviceId, $appsflyid);
            }
        }
        //appflysid不变更，再去af-log信息表里校验一下设备安装时间
        if (!empty($deviceInfo) && $appsflyid != "" && $deviceInfo['appsfly_id'] == $appsflyid) {
            
            $systemData->syncAppsflyid($deviceInfo, $appsflyid);
        }
        $this->dataSystem->setFirstOpenNx($deviceId, 3600);

        $userId = $this->getTokenUser();
        if ($userId) {
            $this->dataUser->setActive($userId);
        }

        $this->dataUser->openLog($userId ?? 0, $ip, $deviceId);

        //元素法典
        $data['element_url'] = "https://docs.qq.com/doc/DWGh4QnZBVlJYRkly";

        if ($userId) {
            $userData = $this->dataUser->getUser($userId);
            // 首页不弹出
            $version = $this->getVersion();
            if (version_compare($version,'1.0.9') > 0) {
                return $this->buildReturn(Code::SUCCESS, $data);
            }
            $firstOpen = $this->dataSystem->getFirstOpen($deviceId);
            $curTime = time();
            if ($userData['vip_surplus'] == 0 && $curTime - $firstOpen > 3600) {
                $data['discount_time'] = 60;
                $this->dataSystem->setFirstOpen($deviceId);
            }
        }

        Log::info("init.",["device_id" => $deviceId,"user_id" => $userId,"platform" => $this->getPlatform(),"version" => $this->getVersion()]);
        //检查下需要更新的订单
        if($this->checkNoLoginPay() && $userId > 0) {
            (new Pay())->updateUserIdByDeviceId($deviceId, $userId, $this->getPlatform());
        }

        return $this->buildReturn(Code::SUCCESS, $data);
    }

    public function getDiscount(Request $request) {
        $this->validate($request, [
            'type' => ['required'],
        ]);
        $type = $request->get('type');
        $data = [];
        //$dataSystem = new System();
        //$dataUser = new User();
        $deviceId = $this->getDeviceId();
        $this->dataSystem->setFirstOpenNx($deviceId, 3600);
        $userId = $this->getTokenUser();
        if ($userId) {
            $userData = $this->dataUser->getUser($userId);
            // 首页不弹出
            if (date('Y-m-d',strtotime($userData['created_at'])) != date('Y-m-d') && $type == 1) {
                return $this->buildReturn(Code::SUCCESS, $data);
            }
            // 次日不弹出
            if (date('Y-m-d',strtotime($userData['created_at'])) == date('Y-m-d') && in_array($type,[2,3])) {
                return $this->buildReturn(Code::SUCCESS, $data);
            }
            $firstOpen = $this->dataSystem->getFirstOpen($deviceId);
            $curTime = time();
            if ($userData['vip_surplus'] == 0 && $curTime - $firstOpen > 3600) {
                $data['discount_time'] = 60;
                $this->dataSystem->setFirstOpen($deviceId);
            }
        }
        return $this->buildReturn(Code::SUCCESS, $data);
    }


    public function getPutfileUrl(Request $request) {
        $oss = new Oss();
        $uri = 'uploads/'. $this->getRoundToken() .'.png';
        $putUrl = $oss->get_object_put_url($uri);
        $data = [
            'put_url' => $putUrl,
            'uri' => '/'.$uri,
            'url' => env('APP_FILES_URL') . '/'.$uri
        ];
        return $this->buildReturn(Code::SUCCESS, $data);
    }


    public function adClick(Request $request) {
        $this->validate($request, [
            'channel' => ['required'],
            'source' => ['required'],
        ]);
        $imei = $request->imei ?? '';
        $imei5 = $request->imei5 ?? '';
        $idfa = $request->idfa ?? '';
        $idfa5 = $request->idfa5 ?? '';
        $oaid = $request->oaid ?? '';
        $oaid5 = $request->oaid5 ?? '';
        $ip = $request->ip ?? '';
        $ip5 = $request->ip5 ?? '';
        $cburl = $request->cburl ?? '';
        $os = $request->os ?? '';
        $channel = $request->channel ?? '';
        $source = $request->source ?? '';

        $systemData = new System();
        if (!empty($imei)) {
            $systemData->setAdTag($imei, $cburl, $channel, $source, $os);
        }
        if (!empty($imei5)) {
            $systemData->setAdTag($imei5, $cburl, $channel, $source, $os);
        }
        if (!empty($idfa)) {
            $systemData->setAdTag($idfa, $cburl, $channel, $source, $os);
        }
        if (!empty($idfa5)) {
            $systemData->setAdTag($idfa5, $cburl, $channel, $source, $os);
        }
        if (!empty($oaid)) {
            $systemData->setAdTag($oaid, $cburl, $channel, $source, $os);
        }
        if (!empty($oaid5)) {
            $systemData->setAdTag($oaid5, $cburl, $channel, $source, $os);
        }
        if (!empty($ip)) {
            $systemData->setAdTag($ip, $cburl, $channel, $source, $os);
        }
        if (!empty($ip5)) {
            $systemData->setAdTag($ip5, $cburl, $channel, $source, $os);
        }
    }

    public function update(Request $request) {
        $this->validate($request, [
            'version_code' => ['required'],
            'version' => ['required'],
        ]);

        $version = $request->version ?? '';
        $channelId = $this->getChannel();

        $channelData = Upgrade::getChannelData($channelId);

        //判断版本是否是最新
        if ($channelData) {
            version_compare($version, $channelData->version);
            if (version_compare($version, $channelData->version) == 0) {
                $channelData->type = 0;
            }
        }
        return $this->buildReturn(Code::SUCCESS, $channelData);

    }

    // 获取预估时长
    public function getEstimateTime() {
        $systemData = new System();
        $hostSize = $systemData->getHostSize();
        $queueSize = $systemData->getQueueSize();
        return $queueSize*8/$hostSize;
    }

    // 获取队列数据
    public function getEstimate() {
        $systemData = new System();
        $hostSize = $systemData->getHostSize();
        $queueSize = $systemData->getQueueSize();
        return [$hostSize, $queueSize];
    }

    //上传文件
    public function uploadFile(Request $request)
    {
        if (!$request->hasFile('file')) {
            return $this->buildReturn(Code::PARAM_ERROR, [], '参数错误');
        }

        $file = $request->file('file');
        $path = $request->file->path();

        $format = $file->getClientOriginalExtension();
        if (!in_array($format, ['jpg', 'jpeg', 'gif', 'png', 'webp'])) {
            return $this->buildReturn(Code::PARAM_ERROR, [], '参数错误');
        }

        $oss = new Oss();
        $uri = 'uploads/'. $this->getRoundToken() .'.png';
        $putUrl = $oss->get_object_put_url($uri);
        $data = [
            'put_url' => $putUrl,
            'uri' => '/'.$uri,
            'url' => env('APP_FILES_URL') . '/'.$uri
        ];

        $curl = new CurlCommon();
        $updateres = $curl->curl_upload( $putUrl , '' , '' , 'put'  , $path );
        if ($updateres['code'] != 200) {
            return $this->buildReturn(Code::SYSTEM_UPLOAD_ERROR, [], Code::$msg[Code::SYSTEM_UPLOAD_ERROR]);
        }

        return $this->buildReturn(Code::SUCCESS, $data);
    }

    /**
     * @desc 用户行为记录
     */
    public function event(Request $request)
    {
        $data = file_get_contents("php://input");
        Log::info("userEventLog", ["data" => $data]);
        $params = [];
        parse_str($data,$params);

		$event_params = isset($params["event_params"]) ? $params["event_params"] : null;
        if(empty($event_params)) {
            return $this->buildReturn(Code::SUCCESS);
        }
        $event_params = json_decode($event_params,true);
        $data = [
            "created_time" => date("Y-m-d H:i:s"),
            "platform" => $this->getPlatform() == 1 ? "ios" : "android",
            "ver_name" => $this->getVersion(),
            "device_id" => $this->getDeviceId(),
            "name" => trim($params["event_name"]),
            "type" => trim($params["event_type"]),
        ];

        $insert = false;
        foreach ($event_params as $key => $val) {
            if (empty($val)) {
                continue;
            }
            //$data[strtolower($key)] = $val;
            $data[strtolower($key)] = is_string($val)?$val:json_encode($val);
            $insert = true;
        }

        if ($insert) {
            EventList::getInstance()->addData($data);
        }

        return $this->buildReturn(Code::SUCCESS);
    }

    public function getRequest(Request $request)
    {
        $ip = $this->getRealIp();
        $res = $this->dataSystem->is_ip_in_china($ip);
        $requestUrl = $res ? env('APP_URL') : env('OVERSEAS_URL');
        return $this->buildReturn(Code::SUCCESS, ['url' => $requestUrl]);
    }

    public function afGoogleNotify(Request $request) {
        $content = file_get_contents('php://input');
        Log::info("afNotify_google", ['af通知数据：' => $content]);
        AfLog::getInstance()->addLog($content,2);
    }

    public function afAppleNotify(Request $request) {
        $content = file_get_contents('php://input');
        Log::info("afNotify_apple", ['af通知数据：' => $content]);
        AfLog::getInstance()->addLog($content,1);
    }

    public function index() {
        $return = [
            "is_pay" => false,
            "is_login" => false,
        ];

        $deviceId = $this->getDeviceId();
        $userId = $this->getTokenUser();
        $platform = $this->getPlatform();
        $payCount = 0;
        $ontrialInfo = [];

        $ontrialObj = new UserOntrial();
        $pay = new Pay();

        if ($userId) {
            $return["is_login"] = true;
            $payCount = $pay->getUserCount($userId);
            if ($payCount < 1) {
                $ontrialInfo = $ontrialObj->getStatus($userId);
            }
        } else {
            $payCount = $pay->getDeviceIdCount($deviceId,$platform);
            if ($payCount < 1) {
                $ontrialInfo = $ontrialObj->getStatusByDeviceId($deviceId);
            }
        }
        Log::info("system/index",["ontrialInfo" => $ontrialInfo,"device_id" => $deviceId,"user_id" =>$userId,"payCount" => $payCount]);
        //兼容下适用的数据
        if ($payCount < 1) {
            $check = $ontrialObj->checkValid($ontrialInfo);
            Log::info("ontria_check",["ontrialInfo" => $ontrialInfo,"check" => $check]);
            $payCount = $check ? 1 : $payCount;
        }
        Log::info("system/index1",["ontrialInfo" => $ontrialInfo,"device_id" => $deviceId,"user_id" =>$userId,"payCount" => $payCount]);
        $return["is_pay"] = $payCount > 0 ? true : false;

		//是否有升级
		//$return["is_update"] = version_compare(env("LASEST_VERSION"), $this->getVersion()) > 0 ? true : false;
		$bIsUpdate = version_compare('1.9.1', $this->getVersion()) > 0 ? true : false;

		$return["is_update"] = false;
		$return["is_force_update"] = false;//是否强制更新

		//@todo Test
		if(1 == $platform) {//iOS
			$return["is_update"] = $bIsUpdate;
		} else {
			$return["is_update"] = $bIsUpdate;
			$return["is_force_update"] = false;
		}
        $return['is_old_vip'] = (new User())->getIsOldVip($userId, $deviceId);//判断是否是非会员老用户

        return $this->buildReturn(Code::SUCCESS,$return);
    }

	/**
	 * 订阅页顶部轮播图
	 */
    public function subscribeTop() {
        $return = [];
		$sPlatform = $this->getPlatform();
		if(1 == $sPlatform) {
			$return["imgs"] = [
				'https://overseas-files.dalleai.art/buy_dot_top/1.png',
				'https://overseas-files.dalleai.art/buy_dot_top/2.png',
				'https://overseas-files.dalleai.art/buy_dot_top/5.png',
			];
		}else{
			$return["imgs"] = [];
			for ($i = 1;$i <= 5;$i++) {
				$return["imgs"][] = env("APP_FILES_URL")."/subscribe_top/{$i}.webp?v=3";
			}
		}

        return $this->buildReturn(Code::SUCCESS,$return);
    }
}